<template>
  <div class="page">
    <h2>儿童与青少年心理管理</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/档案号/症状搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="ageGroup" placeholder="年龄段" style="width:160px">
        <el-option label="全部年龄" :value="''" />
        <el-option label="0-5岁" value="0-5" />
        <el-option label="6-12岁" value="6-12" />
        <el-option label="13-18岁" value="13-18" />
      </el-select>

      <el-select v-model="statusFilter" placeholder="就诊状态" style="width:140px">
        <el-option label="全部状态" :value="''" />
        <el-option label="随访中" value="followup" />
        <el-option label="已结案" value="closed" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增档案</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="recordId" label="档案号" width="140" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="screening" label="筛查/量表" width="180" />
      <el-table-column prop="symptoms" label="主诉/症状" />
      <el-table-column prop="assigned" label="随访医师" width="140" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status==='followup' ? 'warning' : 'success'">{{ row.status==='followup' ? '随访中' : '已结案' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.recordId)">编辑</el-button>
          <el-button size="small" @click="markClosed(row.recordId)" style="margin-left:8px">结案</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.recordId)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchMarkClosed">批量结案</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑档案' : '新增档案'" v-model="showModal" width="600px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="档案号">
          <el-input v-model="form.recordId" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄/性别">
          <div style="display:flex;gap:8px">
            <el-input-number v-model="form.age" :min="0" style="width:120px" />
            <el-select v-model="form.gender" placeholder="性别" style="width:120px">
              <el-option label="男" value="M" />
              <el-option label="女" value="F" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="筛查量表">
          <el-select v-model="form.screening" style="width:260px">
            <el-option label="儿童行为量表(CBCL)" value="CBCL" />
            <el-option label="儿童抑郁量表(CDI)" value="CDI" />
            <el-option label="青少年焦虑量表(SCAS)" value="SCAS" />
          </el-select>
        </el-form-item>
        <el-form-item label="主诉/症状">
          <el-input v-model="form.symptoms" />
        </el-form-item>
        <el-form-item label="随访医师">
          <el-input v-model="form.assigned" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="随访中" value="followup" />
            <el-option label="已结案" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="随访计划">
          <el-input v-model="form.plan" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  { recordId: 'CY0001', name: '张小明', age: 8, gender: 'M', screening: 'CBCL', symptoms: '注意力不集中、易怒', assigned: '李医生', status: 'followup', plan: '每月随访' },
  { recordId: 'CY0002', name: '王晓华', age: 15, gender: 'F', screening: 'SCAS', symptoms: '回避社交、睡眠差', assigned: '赵医生', status: 'followup', plan: '行为干预+家长培训' },
  { recordId: 'CY0003', name: '李思思', age: 4, gender: 'F', screening: 'CBCL', symptoms: '发育迟缓', assigned: '陈医生', status: 'closed', plan: '完成随访' }
];

const data = ref([]);
const q = ref('');
const ageGroup = ref('');
const statusFilter = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ recordId:'', name:'', age:0, gender:'M', screening:'', symptoms:'', assigned:'', status:'followup', plan:'' });

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || String(d.recordId).toLowerCase().includes(qq) || (d.symptoms||'').toLowerCase().includes(qq))) return false;
    if(ageGroup.value){ const ag = ageGroup.value; if(ag==='0-5' && d.age>5) return false; if(ag==='6-12' && (d.age<6||d.age>12)) return false; if(ag==='13-18' && (d.age<13||d.age>18)) return false; }
    if(statusFilter.value && d.status !== statusFilter.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.recordId); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.recordId===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{recordId:'',name:'',age:0,gender:'M',screening:'',symptoms:'',assigned:'',status:'followup',plan:''}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.recordId || !form.name){ ElMessage.warning('档案号和姓名为必填项'); return; }
  if(editingId.value){ const it = data.value.find(x=>x.recordId===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); }
  else{ data.value.push(JSON.parse(JSON.stringify(form))); }
  showModal.value=false; ElMessage.success('保存成功'); }

function deleteOne(id){ ElMessageBox.confirm('确认删除该档案？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.recordId!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function markClosed(id){ const it = data.value.find(x=>x.recordId===id); if(it){ it.status='closed'; ElMessage.success('已结案'); } }
function batchMarkClosed(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.recordId)) d.status='closed'; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条档案？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.recordId)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['recordId','name','age','gender','screening','symptoms','assigned','status','plan'], ...data.value.map(d=>[d.recordId,d.name,d.age,d.gender,d.screening,d.symptoms||'',d.assigned||'',d.status,d.plan||'']) ];
  const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='children_youth.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function onClear(){}
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>